package com.zhx.ad.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhx.ad.common.exception.AdException;
import com.zhx.ad.constants.Constants;
import com.zhx.ad.entity.AdUser;
import com.zhx.ad.mapper.AdUserMapper;
import com.zhx.ad.service.IAdUserService;
import com.zhx.ad.utils.CommonUtils;
import com.zhx.ad.client.vo.CreateUserRequest;
import com.zhx.ad.client.vo.CreateUserResponse;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *describe: 
 *
 *@author zhanghaixuan
 *@date 2019/02/02
 **/
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

	@Override
	public AdUser findByUsername(String username) {
		return baseMapper.findByUsername(username);
	}


	@Override
	@Transactional
	public CreateUserResponse createUser(CreateUserRequest request)
			throws AdException {

		if (!request.validate()) {
			throw new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
		}

		AdUser oldUser =  findByUsername(request.getUsername());
		if (oldUser != null) {
			throw new AdException(Constants.ErrorMsg.SAME_NAME_ERROR);
		}

		AdUser newUser = new AdUser(
				request.getUsername(), CommonUtils.md5(request.getUsername())
		);

		save(newUser);

		return new CreateUserResponse(
				newUser.getId(), newUser.getUsername(), newUser.getToken(),
				newUser.getCreateTime(), newUser.getUpdateTime()
		);
	}
}
